<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopStatisticsModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\ConsoleOutput;

class StatisticsSignToPosition extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:statistics_sign_to_position';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计门店的落位时常';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        // 统计每个订单 门店的落位时常

        $countTask = OpenShopSiteMissionModel::query()
            ->where('mainStep', MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION)
            ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_5)
            ->count();

        $consoleOutput = new ConsoleOutput();

        $progressBar = new ProgressBar($consoleOutput, (int)ceil($countTask / 100));

        // 启动进度条
        $progressBar->start();

        OpenShopSiteMissionModel::query()
            ->where('mainStep', MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION)
            ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_5)
            ->chunk(100, function ($siteMissionModels) use ($progressBar){
                $progressBar->advance();
                $insertData = [];
                foreach ($siteMissionModels as $siteMissionModel) {

                    // 判断订单状态
                    $signOrderModel = OpenShopSignOrderModel::query()
                        ->where('orderNo', $siteMissionModel->orderNo)
                        ->first();

                    // 过滤作废订单
                    if ($signOrderModel == null) {
                        continue;
                    }

                    if ($signOrderModel->status == SignOrderEnum::ORDER_STATUS_NO) {
                        continue;
                    }
                    if ($signOrderModel->shopCode == 0) {
                        continue;
                    }


                    // 签约时间
                    $signTime = (int)OpenShopUserContractModel::query()
                        ->where('orderNo', $siteMissionModel->orderNo)
                        ->value('signTime');


                    // 落址时间
                    $positionTime = $siteMissionModel->completeAt;

                    if (!$signTime || !$positionTime) {
                        continue;
                    }

                    try {
                        // 统计时长
                        $diffDays = Carbon::createFromTimestamp($signTime)->diffInDays(Carbon::createFromTimestamp($positionTime));
                    } catch (\Exception $exception) {
                        continue;
                    }

                    $insertData[] = [
                        'type'        => OpenShopStatisticsModel::TYPE_TIME,
                        'orderNo'     => $siteMissionModel->orderNo,
                        'statistics'  => '落位时长',
                        'beforeValue' => $signTime,
                        'nowValue'    => $positionTime,
                        'addition'    => $diffDays,
                        'createdAt'   => time(),
                        'updatedAt'   => time(),
                    ];
                }

                if (count($insertData)) {
                    OpenShopStatisticsModel::query()->insert($insertData);
                }

            });

        $progressBar->finish();

        // 输出换行符，让结果更美观
        $consoleOutput->writeln('');
    }
}
